#include "taskrecord.h"
#include <QVariant>
#include <QSqlField>
#include <QSqlRecord>
#include <QDebug>

void TaskRecord::initFields() {
    record->append(QSqlField("id", QVariant::Int));
    record->append(QSqlField("url", QVariant::String));
    record->append(QSqlField("path", QVariant::String));
    record->append(QSqlField("size", QVariant::Int));
    record->append(QSqlField("downloaded_size", QVariant::Int));
    record->append(QSqlField("priority", QVariant::Int));
    record->append(QSqlField("status", QVariant::Int));

    record->setValue("url", "");
    record->setValue("path", "");
    record->setValue("size", 0);
    record->setValue("downloaded_size", 0);
    record->setValue("priority", 0);
    record->setValue("status", 0);
}

TaskRecord::TaskRecord(QObject* parent)
    : QObject(parent)
    , status_(NEW)
    , record(new QSqlRecord)
{
    initFields();
}

void TaskRecord::setId(int id)
{
    id_ = id;
    record->setValue("id", id_);
}

int TaskRecord::getId() const
{
    return id_;
}

TaskRecord::TaskRecord(const QString& url, const QString& path, int priority, QObject* parent)
    : QObject(parent)
    , status_(NEW)
    , url_(url)
    , path_(path)
    , priority_(priority)
    , record(new QSqlRecord)
{
    initFields();

    record->setValue("url", url_);
    record->setValue("path", path_);
    record->setValue("priority", priority_);
}

QSqlRecord& TaskRecord::getRecord() const
{
    return *record;
}

QString TaskRecord::getURL() const
{
    return url_;
}

QString TaskRecord::getPath() const
{
    return path_;
}

int TaskRecord::getPriority() const
{
    return priority_;
}

void TaskRecord::resetStatus()
{
    record->setValue("size", 0);
    record->setValue("downloaded_size", 0);
    updateStatus(NEW);
}

void TaskRecord::updateStatus(TaskRecord::status_t status)
{
    record->setValue("status", status);
    status_ = status;
    emit taskUpdated(id_, record);
}

void TaskRecord::updateProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    qDebug() << bytesReceived << " / " << bytesTotal;
    record->setValue("downloaded_size", bytesReceived);
    record->setValue("size", bytesTotal);
    emit taskUpdated(id_, record);
}
